package com.yfore.jfinal.jsql.plugin;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.IPlugin;
import com.yfore.jfinal.jsql.plugin.core.SqlMapping;
import com.yfore.jfinal.jsql.plugin.xml.JSql;
import com.yfore.jfinal.jsql.plugin.xml.JSqlConfig;
import com.yfore.jfinal.jsql.plugin.xml.JSqlPath;
import com.yfore.jfinal.jsql.plugin.xml.Sql;
import com.yfore.jfinal.jsql.plugin.xml.util.JsqlXmlUtil;

/**
 * Jsql插件
 * @author farmer
 *
 */
public class JSqlPlugin implements IPlugin{
	
	InputStream in = null;
	
	/**
	 * 
	 * @param configPath
	 */
	public JSqlPlugin(String configPath) {
		this(JSqlPlugin.class.getResourceAsStream(configPath));
	}
	
	/**
	 * 
	 */
	public JSqlPlugin(InputStream in) {
		this.in = in;
	}
	
	@Override
	public boolean start() {
		JSqlConfig jSqlConfig = JsqlXmlUtil.toJSqlConfig(in);
		List<JSql> jSqls = new ArrayList<JSql>();
		for (JSqlPath jSqlPath : jSqlConfig.getJsqlpaths()) {
			jSqls.add(JsqlXmlUtil.toJSql(getClass().getResourceAsStream(jSqlPath.getPath())));
		}
		for (JSql jSql : jSqls) {
			String namespace = jSql.getNamespace();
			List<Sql> sqls = jSql.getSqls();
			for (Sql sql : sqls) {
				SqlMapping.put(namespace+"."+sql.getId(), sql.getSql());
			}
		}
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}
	
}
